from __future__ import absolute_import

import md5
from . import token
from scopt.util.misc import unique_id
from scopt.util import message as msg_util
from scopt.util.message_types import STRING


@token(version='0.1',
       token={'type': 'security.authenticate.login.password',
              'login': STRING(required=True),
              'password': STRING(required=True)},
       resd={'token': STRING(required=True),
             'principal': {'login': STRING(required=True),
                           'username': STRING(required=True)}})
def handle(data_packet, registry):
    security_token = msg_util.get_security_token(data_packet)
    result = _validate(security_token['login'],
                       security_token['password'], registry)
    if msg_util.result_is_error(result):
        return msg_util.exception(data_packet, result[1])
    resd = {'token': result['token_string'],
            'principal': {'login': result['login'],
                          'username': result['username']}}
    data_packet = msg_util.ok_response(data_packet, handle, resd)
    return msg_util.finish_data_packet(data_packet)


def _validate(login, password, registry):
    md5pwd = md5.new(password).hexdigest()
    result = registry.query('users',
                            where=[['users.login', login],
                                   ['users.md5pwd', md5pwd]])
    if len(result) == 0:
        return ('ERROR', 'security.invalid.login.password', None)
    token_string = unique_id()
    registry.update('users',
                    values={'token': token_string},
                    where=[['users.login', login]])
    user = result[0]
    login = 'ADMIN' if user['admin'] else user['login']
    return {'token_string': token_string,
            'login': login,
            'username': user['username']}
